Digital Input with Buttons

The digital inputs pins on the Pico can be used to read the state of a digital device (such as a button).

Buttons and switches come in various shapes and sizes. We will use these simple 'momentary' buttons which fit nicely in a breadboard.


Wire up (pull down)

Connect the button to a breadboard as follows:

Wire up pull down
Circuit Pico
Red 3V3
Blue GP18 or another GP pin

Code (pull down)

Write this code and download to the Pico. The output will change according to whether the button is pressed or not.

See code on github
# Test button input (button connected to 3V3)

import board
from digitalio import DigitalInOut, Direction, Pull
import time

# Set up the button on pin 18 as a digital input pin
switch = DigitalInOut(board.GP18)
switch.direction = Direction.INPUT
switch.pull = Pull.DOWN               # Pull down so button value is True when pressed

# Show the button status (True is pressed, False is not pressed)
while True:
    print(switch.value)
    time.sleep(0.01)

The above circuit and code uses the "pull down" approach, where the pin defaults to 0 (False) when not pressed and changes to 1 (True) when the button is pressed and the connection to 3V3 is made.

An alternative is the "pull up" approach, where the pin defaults to 1 (True) when not pressed and changes to 0 (False) when the button is pressed and the connection to GND is made. This approach is explained below.

Wire up (pull up)

Connect the button to a breadboard as follows:

Wire up pull up
Circuit Pico
Black GND
Blue GP18 or another GP pin

Code (pull up)

Write this code and download to the Pico. The output will change according to whether the button is pressed or not.

# Test button input (button connected to ground)

import board
from digitalio import DigitalInOut, Direction, Pull
import time

# Set up the button on pin 18 as a digital input pin
switch = DigitalInOut(board.GP18)
switch.direction = Direction.INPUT
switch.pull = Pull.UP               # Pull up so button value is True when not pressed

# Show the button status (False is pressed, True is not pressed)
while True:
    print(switch.value)
    time.sleep(0.01)